#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
文件工具类
@author weiximei
@date 2025/2/28
"""
import os
from typing import List, Union


def read_file(file_path: str, encoding: str = 'utf-8') -> str:
    """
    读取文件全部内容
    :param file_path: 文件路径
    :param encoding: 编码格式
    :return: 文件内容
    """
    with open(file_path, 'r', encoding=encoding) as f:
        return f.read()


def read_lines(file_path: str, encoding: str = 'utf-8') -> List[str]:
    """
    按行读取文件内容
    :param file_path: 文件路径
    :param encoding: 编码格式
    :return: 文件内容行列表
    """
    with open(file_path, 'r', encoding=encoding) as f:
        return f.readlines()


def read_file_chunk(file_path: str, chunk_size: int = 1024, encoding: str = 'utf-8') -> str:
    """
    分块读取大文件
    :param file_path: 文件路径
    :param chunk_size: 每次读取的块大小
    :param encoding: 编码格式
    :return: 生成器，逐块返回文件内容
    """
    with open(file_path, 'r', encoding=encoding) as f:
        while True:
            chunk = f.read(chunk_size)
            if not chunk:
                break
            yield chunk


def write_file(file_path: str, content: Union[str, List[str]], encoding: str = 'utf-8', append: bool = False) -> None:
    """
    写入文件内容
    :param file_path: 文件路径
    :param content: 要写入的内容，可以是字符串或字符串列表
    :param encoding: 编码格式
    :param append: 是否追加模式
    """
    mode = 'a' if append else 'w'
    with open(file_path, mode, encoding=encoding) as f:
        if isinstance(content, list):
            f.writelines(content)
        else:
            f.write(content)


def ensure_dir(file_path: str) -> None:
    """
    确保文件所在目录存在，如果不存在则创建
    :param file_path: 文件路径
    """
    directory = os.path.dirname(file_path)
    if directory and not os.path.exists(directory):
        os.makedirs(directory)
